package dm.ass1.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.io.Writable;

public class ProfileWritable implements Writable{

	private int rater;
	private int[] rated;
	private int[] rating;
	
	public ProfileWritable() {
	}
		
	public ProfileWritable(int rater, int[] rated, int[] rating) {
		super();
		this.rater = rater;
		this.rated = rated;
		this.rating = rating;
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		this.rater = in.readInt(); 
		int numOfRatings = in.readInt();
		this.rated = new int[numOfRatings];
		for (int i = 0; i < numOfRatings; i++) {
			rated[i] = in.readInt();
		}
		this.rating = new int[numOfRatings];
		for (int i = 0; i < numOfRatings; i++) {
			rating[i] = in.readInt();
		}
	}
	
	public int getRater() {
		return rater;
	}
	
	public int[] getRated() {
		return rated;
	}

	public int[] getRating() {
		return rating;
	}
	

	@Override
	public void write(DataOutput out) throws IOException {
		out.writeInt(this.rater);
		out.writeInt(rated.length);
		for (int rated : this.rated) {
			out.writeInt(rated);
		}
		for (int rating : this.rating) {
			out.writeInt(rating);
		}
		
	}
		
	@Override
	public String toString() {
		StringBuilder out = new StringBuilder();
		out.
		 //append(this.rater).
		 //append(" ").
		 append(Arrays.toString(this.rated).replaceAll(" ", "")).
		 append(" ").
		 append(Arrays.toString(this.rating).replaceAll(" ", ""));

		return out.toString();
	}
	
	public static ProfileWritable fromString(String line) {
		ProfileWritable profile = null;
		
		int rater;
		int[] rated;
		int[] rating;
		
		String[] lineArray = line.split("[ \\t]");
		rater = Integer.parseInt(lineArray[0]);
		
		String[] ratedStringArray = lineArray[1].substring(1, lineArray[1].length() - 1).split(",");
		rated = new int[ratedStringArray.length];
		for (int i = 0; i < ratedStringArray.length; i++) {
			rated[i] = Integer.parseInt(ratedStringArray[i].trim());
		}
		
		String[] ratingStringArray = lineArray[2].substring(1, lineArray[2].length() - 1).split(",");
		rating = new int[ratingStringArray.length];
		for (int i = 0; i < ratingStringArray.length; i++) {
			rating[i] = Integer.parseInt(ratingStringArray[i].trim());
		}
		
		profile = new ProfileWritable(rater, rated, rating);
		
		return profile;
	}
}
